package cn.jiemusic.controller;

import cn.jiemusic.common.CustomException;
import cn.jiemusic.common.R;
import cn.jiemusic.domain.dto.ChangePWDto;
import cn.jiemusic.domain.dto.RegUserDto;
import cn.jiemusic.domain.dto.UserCodeDto;
import cn.jiemusic.domain.po.User;
import cn.jiemusic.service.UserService;
import cn.jiemusic.utils.JWTUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/reg")
    public R<String> reg(HttpServletRequest req, @RequestBody RegUserDto regUserDto) {
        String code = req.getSession().getAttribute("code").toString();

        if (!code.equalsIgnoreCase(regUserDto.getCode()))
            throw new CustomException("验证码异常");

        userService.reg(regUserDto);

        return R.success("注册成功");
    }

    @PostMapping("/login")
    public R<String> login(HttpServletRequest req, @RequestBody User user) {
        if (user.getPassword().length() != 32) throw new CustomException("密码解析错误");
        //将密码加密
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPassword, password);
        queryWrapper.eq(User::getUsername, user.getUsername());

        User one = userService.getOne(queryWrapper);

        if (one == null) return R.error("账号密码错误，请重新尝试");

        //生成JWT令牌
        String jwt = JWTUtils.generateJwt(one, password);

        return R.success(jwt);
    }

    @PostMapping("/find-username")
    public R<String> checkUser(HttpServletRequest req, @RequestBody UserCodeDto userCodeDto) {
        String code = req.getSession().getAttribute("code").toString();

        if (!code.equalsIgnoreCase(userCodeDto.getCode()))
            throw new CustomException("验证码异常");

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, userCodeDto.getUsername());

        if (userService.count(queryWrapper) != 1) throw new CustomException("用户不存在");

        return R.success("查有此人...");
    }

    @PutMapping("/change-pw")
    public R<String> changePW(@RequestBody ChangePWDto changePWDto) {

        if (changePWDto.getPassword().length() != 32) throw new CustomException("密码解析错误");
        //对密码进行加密
        String password = DigestUtils.md5DigestAsHex(changePWDto.getPassword().getBytes());
        changePWDto.setPassword(password);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, changePWDto.getUsername());
        queryWrapper.eq(User::getEmail, changePWDto.getEmail());

        User user = userService.getOne(queryWrapper);
        if (user == null) throw new CustomException("更新失败");

        user.setPassword(password);
        userService.updateById(user);

        return R.success("修改成功");
    }

    @GetMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        // 销毁当前会话
        request.getSession().invalidate();
        return R.success("用户已成功退出！");
    }
}
